from socket import socket

from threading import Thread
from time import sleep
#引入crcmod模块
import crcmod



def tcprecv():
    while True:
        data = mysocket.recv(1024)
        if not data:
            break
        print("接受报文：%s",data.hex())


if __name__ == "__main__":
    mysocket = socket()
    mysocket.connect(("172.27.0.113",5000))

    print("hello")
    _RESP = bytes.fromhex(
        "02 03 00 1E 00 01 E4 3F ")
    _r = bytes.fromhex(
        "68 00 01 67 20 30 09 68 91 0A 33 32 34 35 33 33 A4 55 33 33 BF 16 "
)
    threadrecv = Thread(target = tcprecv)
    threadrecv.start()
    while True:
        request = input("输入RTU报文：")
        rtu = bytes.fromhex(request)
        #添加crc16校验
        crc16_func = crcmod.mkCrcFun(0x18005, initCrc=0xFFFF, xorOut=0x0000)
        crc = crc16_func(rtu)
        crc = crc.to_bytes(2, byteorder='little')
        rtu = rtu + crc
        
        mysocket.send(rtu)
        sleep(1)
        print("发送报文：%s",rtu)

